<?php

declare(strict_types=1);

namespace app\api\model;

/**
 * 小节模型
 */
class Section extends Base
{
    protected $autoWriteTimestamp = 'datetime';

    /**
     * # 获取章节下小节
     * @param string|array|int $chapter_ids
     * @param string $order
     * @param string $option
     * @return false|object
     */
    public static function getSection($chapter_ids, $order = 'desc', $option = 'select')
    {
        $field = 'id,title,status';
        $where = [];
        if (is_string($chapter_ids) || is_int($chapter_ids)) {
            $where[] = ['chapter_id', '=', $chapter_ids];
        } else if (is_array($chapter_ids)) {
            $where[] = ['chapter_id', 'in', $chapter_ids];
        } else {
            return false;
        }
        $chapter = Section::where($where)->field($field)->order('id', $order)->$option();
        return $chapter;
    }

    /**
     * 获取小节内容
     */

    public static function getContent($id)
    {
        $section = Section::find($id);
        if (empty($section)) {
            return [];
        }
        return [
            'content' => $section->content
        ];
    }

    /**
     * 
     * 删除小节
     */

    public static function delSection($id)
    {
        $section = Section::find($id);
        if (empty($section)) {
            return [
                'code' => 404,
                'message' => '删除失败,数据不存在'
            ];
        }
        if ($section->delete() === true) {
            return [
                'code' => 200,
                'message' => '删除成功'
            ];
        } else {
            return [
                'code' => 404,
                'message' => '删除失败'
            ];
        }
    }

    /**
     * 
     * 新增小节
     */

    public static function addSection($data)
    {
        $success = Section::create($data);
        return $success;
    }

    /**
     * 
     * 修改小节
     */
    public static function updateSection($data)
    {
        $section = Section::find($data['id']);
        if (empty($section)) {
            return [
                'code' => 404,
                'message' => '数据不存在'
            ];
        }
        $section->title = $data['title'];
        $section->content = $data['content'];
        $section->status = $data['status'];
        if ($section->save() === true) {
            $message = $data['status'] == 0 ? '已存为草稿' : '修改成功';
            return [
                'code' => 200,
                'message' => $message,
            ];
        } else {
            return [
                'code' => 404,
                'message' => '修改失败',
            ];
        }
    }
}
